import { Observable } from "rxjs";

export function fromSSE(url: string, withCredentials = false) {
  if ("EventSource" in window) {
    let source = new EventSource(url, { withCredentials });
    const observable = new Observable((subscriber) => {
      source.addEventListener("open", event => {
        subscriber.next({ type: 'open', event });
      });
      source.addEventListener("message", event => {
        subscriber.next({ type: 'message', event });
      });
      source.addEventListener("error", event => {
        subscriber.error(event);
      })
    })
    return observable;
  }
}
